package site.teamo.biu.net.client.configuration;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSON;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import site.teamo.biu.net.client.entity.ConnectionRuleDO;
import site.teamo.biu.net.client.mapper.ConnectionRuleMapper;
import site.teamo.biu.net.client.core.http_https_proxy.TrafficStatistics;
import site.teamo.biu.net.client.core.http_https_proxy.constant.HttpHttpsProxyServiceMode;
import site.teamo.biu.net.common.web.entity.SystemConfig;
import site.teamo.biu.net.common.web.mapper.SystemConfigMapper;
import site.teamo.biu.tool.spring.listener.ApplicationReadyListener;

import java.util.List;

/**
 * @author haocongshun
 * @date 2023/06/07 16:43:35
 */
@Configuration
public class ClientConfiguration {

    public static final SystemConfig CLIENT_ID = new SystemConfig("client-id", "客户端ID", true, () -> HexUtil.encodeHexStr(String.valueOf(IdUtil.getSnowflakeNextId())));
    public static final SystemConfig HTTP_HTTPS_PROXY_SERVICE_MODE = new SystemConfig("http-https-proxy-service-mode", "代理服务连接模式", true, HttpHttpsProxyServiceMode.DIRECT::name);
    public static final SystemConfig HTTP_HTTPS_PROXY_SERVICE_LISTEN_PORT = new SystemConfig("http-https-proxy-service-listen-port", "代理服务配置", true, () -> "19090");
    public static final SystemConfig HTTP_HTTPS_PROXY_SERVICE_USED_SERVER_ID = new SystemConfig("http-https-proxy-service-used-server-id", "代理服务上使用的服务中心id", true, () -> "");
    public static final SystemConfig HTTP_HTTPS_PROXY_SERVICE_TRAFFIC_STATISTICS = new SystemConfig("http-https-proxy-service-traffic-statistics", "代理服务流量统计", true, () -> JSON.toJSONString(new TrafficStatistics()));

    @Resource
    private SystemConfigMapper systemConfigMapper;

    @Resource
    private ConnectionRuleMapper connectionRuleMapper;

    @Autowired
    private ApplicationReadyListener listener;

    @PostConstruct
    public void init() {
        listener.addJob("客户端信息初始化", () -> {
            systemConfigMapper.insertNotExists(CLIENT_ID.toSystemConfigDO());
            systemConfigMapper.insertNotExists(HTTP_HTTPS_PROXY_SERVICE_MODE.toSystemConfigDO());
            systemConfigMapper.insertNotExists(HTTP_HTTPS_PROXY_SERVICE_LISTEN_PORT.toSystemConfigDO());
            systemConfigMapper.insertNotExists(HTTP_HTTPS_PROXY_SERVICE_USED_SERVER_ID.toSystemConfigDO());
            systemConfigMapper.insertNotExists(HTTP_HTTPS_PROXY_SERVICE_TRAFFIC_STATISTICS.toSystemConfigDO());
            //初始化内置规则
            List<ConnectionRuleDO> list = JSON.parseArray(ResourceUtil.readUtf8Str("rule.json"), ConnectionRuleDO.class);
            connectionRuleMapper.insertNotExists(list);
        });
    }
}
